package com.atguigu.daijia.dispatch.xxl.job;

import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.atguigu.daijia.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.daijia.dispatch.service.NewOrderService;
import com.atguigu.daijia.model.entity.dispatch.XxlJobLog;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author zqtao
 */
@Component
public class DispatchJobHandler {

    @Autowired
    private NewOrderService newOrderService;

    @Autowired
    private XxlJobLogMapper xxlJobLogMapper;

    @XxlJob("dispatchJobHandler")
    public void dispatchJobHandler() {
        System.out.println("执行的订单任务为：" + XxlJobHelper.getJobId());
        //保存任务的日志
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(xxlJobLog.getJobId());
        long startTime = System.currentTimeMillis();
        try {
            //执行任务
            Boolean b = newOrderService.executeTask(XxlJobHelper.getJobId());
            xxlJobLog.setStatus(1);
        } catch (Exception e) {
            xxlJobLog.setStatus(0);
            xxlJobLog.setError(ExceptionUtil.getAllExceptionMsg(e));
        } finally {
            int times = (int) (System.currentTimeMillis() - startTime);
            xxlJobLog.setTimes(times);
            xxlJobLog.setCreateTime(new Date());
            xxlJobLog.setUpdateTime(new Date());
            xxlJobLogMapper.insert(xxlJobLog);
        }
    }


}
